package one.bugu.zookeeper.rpc.framework.aspect;

import one.bugu.zookeeper.rpc.framework.annotations.RpcClient;
import one.bugu.zookeeper.rpc.framework.client.socket.ClientRequestPool;
import com.google.gson.Gson;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

/**
 * Created with IntelliJ IDEA.
 * User: LangK
 * Created Date 2019/2/12
 * Time: 18:28
 * Description:
 */
@Aspect
@Component
public class ClientAspect {

    @Autowired
    private ClientRequestPool clientRequestPool;


    private Gson gson = new Gson();

    private Logger logger = LoggerFactory.getLogger(ClientAspect.class);

    /**
     * 切入所有注有RpcClient注解实体类的方法
     * @param pjp
     * @return
     * @throws Throwable
     */
    @Around("@within(one.bugu.zookeeper.rpc.framework.annotations.RpcClient)")
    public Object doSocket(ProceedingJoinPoint pjp) throws Throwable {
        RpcClient an = (RpcClient) pjp.getSignature().getDeclaringType().getAnnotation(RpcClient.class);
        String serverName = an.serverName();
        String ip = an.serverIp();
        String method = pjp.getSignature().getName();
        String resultObject;
        if (StringUtils.isEmpty(ip)) {
            resultObject = clientRequestPool.send(serverName, method, pjp.getArgs());
        } else {
            resultObject = clientRequestPool.send(serverName, ip, method, pjp.getArgs());
        }
        Object object = pjp.proceed();
        if (resultObject != null) {
            try {
                return gson.fromJson(resultObject, object.getClass());
            } catch (Exception e) {
                logger.info("RPC接收结果转换异常:{}", resultObject);
                return object;
            }
        }
        return object;
    }

}
